const app = getApp()
Page({
	data: {
		result: '数据加载中'
	},
	onLoad(options) {
		this.setData(options)
		app.cloud({
			name: 'shopSetting',
			data: {
				shop_id: this.data.shop_id
			},
			success: res => {
				this.setData({
					result: ''
				})
				this.setData(res.data)
				this.makeLocation()
			},
			fail: res => {
				this.setData({
					result: res.msg
				})
			}
		})
	},
	makeLocation() {
		if (this.data.location && this.data.location.type) {
			this.setData({
				location: {
					longitude: this.data.location.coordinates[0],
					latitude: this.data.location.coordinates[1]
				}
			})
		}
	},
	upload(e) {
		wx.chooseImage({
			count: 1,
			sizeType: ['compressed'],
			success: chooseResult => {
				this.setData({
					[e.currentTarget.dataset.key]: chooseResult.tempFilePaths[0],

				})
			},
		})
	},
	showImg(e) {
		if (this.data[e.currentTarget.dataset.key].substr(0, 8) == 'cloud://') {
			wx.cloud.getTempFileURL({
				fileList: [{
					fileID: this.data[e.currentTarget.dataset.key],
					maxAge: 60 * 60, // one hour
				}]
			}).then(res => {
				console.log(res)
				wx.previewImage({
					urls: res.fileList.map(function (n) {
						return n.tempFileURL
					}),
				})
			})
		} else {
			wx.previewImage({
				urls: [this.data[e.currentTarget.dataset.key]],
			})
		}
	},
	chooseLocation() {
		wx.chooseLocation({
			success: (res) => {
				this.setData({
					address: res.address,
					location: {
						latitude: res.latitude,
						longitude: res.longitude
					}
				})
			},
		})
	},
	onSubmit(e) {
		console.log(e)
		let data = e.detail.value
		if (!data.name) {
			return wx.showToast({
				title: '请输入名称',
				icon: 'none'
			})
		}
		if (!this.data.address) {
			return wx.showToast({
				title: '请选择地址',
				icon: 'none'
			})
		}
		data.address = this.data.address
		data.location = this.data.location
		data.shop_id = this.data.shop_id
		data.op = 'submit'
		wx.showLoading({
		  title: '保存中',
		  mask:true
		})
		let that = this
		new Promise(function (resolver, reject) {
			if (that.data.cover_image && that.data.cover_image.substr(0, 11) == 'http://tmp/') {
				app.upload(that.data.cover_image, 'cover', res => {
					data.cover_image = res.fileID
					console.log('门店照片上传成功', res)
					resolver()
				})
			} else if (that.data.cover_image) {
				data.cover_image = that.data.cover_image
				resolver()
			} else {
				resolver()
			}
		}).then(res => {

			return app.cloud({
				name: 'shopSetting',
				data: data,
				def: true,
				success: res => {
					wx.hideLoading()
					wx.showToast({
						title: '保存成功',
					})

					that.setData(res.data)
					that.makeLocation()

				},
				fail(res) {
					wx.hideLoading()
					wx.showToast({
						title: res.msg,
						icon: 'none'
					})
				}
			})
		})
	}

})